local H = require "packages/activities/HuanhuaFunc"

---队友的遗产
---@param room Room  @ 所在房间
---@param player ServerPlayer @ 执行者
local function Reward(room, player)
  local skill_names = H.getSkills(room, 3)
  if #skill_names == 0 then 
    room:gameOver("") 
    return
  end
  
  local choices = {}
  table.insertTableIfNeed(choices, skill_names)
  table.insert(choices, "DrawTwo")

  local selected_skills = {}
  local choice = room:askForChoice(player, choices, "huanhua_choice", "#huanhua-choose", true)
  
  if not choice or choice == "DrawTwo" then
    player:drawCards(2)
  else
    room:handleAddLoseSkills(player, choice)
    table.insert(selected_skills, choice)
  end
  
  H.returnToSkillPool(room, table.filter(skill_names, function(s) 
    return not table.contains(selected_skills, s) 
  end))
end

---并行选择技能（四人同时选择）
---@param room Room
---@param skill_names string[]
local function ParallelHuanhua(room, skill_names)
  local alive_players = room.alive_players
  local selected_skills = {}
  
  -- 创建并行请求
  local req = Request:new(alive_players, "AskForChoice")
  req.focus_text = "huanhua_choice"
  req.receive_decode = false

  -- 为每个玩家设置选择数据
  for i, p in ipairs(alive_players) do
    local start_idx = (i-1)*3 + 1
    local end_idx = math.min(i*3 + 1, #skill_names)
    local sliced_skills = table.slice(skill_names, start_idx, end_idx)
    
    local choices = {}
    table.insertTableIfNeed(choices, sliced_skills)
    table.insert(choices, "DrawTwo")

    local request_data = { choices, choices, "huanhua_choice", "#huanhua-choose", true }
    req:setData(p, request_data)
    req:setDefaultReply(p, "DrawTwo")
  end

  -- 执行并行请求
  req:ask()

  -- 处理每个玩家的选择结果
  for _, p in ipairs(alive_players) do
    local choice = req:getResult(p)
    if choice == "DrawTwo" then
      p:drawCards(2, "huanhua_choice")
    else
      room:handleAddLoseSkills(p, choice)
      table.insert(selected_skills, choice)
    end
  end

  -- 将未选择的技能返回技能池
  local unused_skills = table.filter(skill_names, function(s) 
    return not table.contains(selected_skills, s) 
  end)
  H.returnToSkillPool(room, unused_skills)
end

local rule = fk.CreateSkill {
  name = "#huanhua_2v2_rule&",
}

-- 一号位首回合额定摸牌数-1
rule:addEffect(fk.DrawNCards, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return target == player and player.seat == 1 and player:getMark(self.name) == 0
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local turnevents = room.logic.event_recorder[GameEvent.Turn] or Util.DummyTable
    if #turnevents == 1 and player:getMark(self.name) == 0 then
      room:setPlayerMark(player, self.name, 1)
      data.n = data.n - 1
    end
  end,
})

-- 四号位多摸一张初始手牌
rule:addEffect(fk.DrawInitialCards, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return target == player and player.seat == 4
  end,
  on_refresh = function(self, event, target, player, data)
    data.num = data.num + 1
  end,
})

-- 构建技能池
rule:addEffect(fk.GameStart, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return target == player
  end,
  on_refresh = function(self, event, target, player, data)
    H.createSkillPool(player.room)
  end,
})

-- 每轮开始时执行幻化（并行选择）
rule:addEffect(fk.RoundStart, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local alive_players = room.alive_players
    local skill_names = H.getSkills(room, 3 * #alive_players)
    
    if #skill_names == 0 then 
      -- 如果技能池空了，给所有玩家摸两张牌
      for _, p in ipairs(alive_players) do
        p:drawCards(2, "huanhua_choice")
      end
      return
    end
    
    -- 使用并行选择
    ParallelHuanhua(room, skill_names)
  end,
})

-- 队友死亡后执行遗产
rule:addEffect(fk.Deathed, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    for _, p in ipairs(room.alive_players) do
      if p.role == player.role then
        Reward(room, p)
      end
    end
  end,
})

-- 结束判定
rule:addEffect(fk.GameOverJudge, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local winner = Fk.game_modes[room.settings.gameMode]:getWinner(player)
    if winner ~= "" then
      room:gameOver(winner)
      return true
    end
  end,
})

Fk:loadTranslationTable{
  ["#huanhua_2v2_rule&"] = "幻化2v2",
  ["huanhua_choice"] = "幻化",
  ["#huanhua-choose"] = "幻化：选择一项技能获得，或摸两张牌",
  ["H_reward"] = "队友的遗产",
  ["H_reward-choosing"] = "遗产：选择一项技能获得"
}

return rule